﻿@inherits ComponentBase
@using GMS.NET.Dto.System.AccRoles.Shared
@inject GMS.NET.Web.Components.Service.Interface.System.IUsersService UserService
@inject GMS.NET.Web.Components.Service.Interface.System.IAccRolesService RoleService

<Form>
    <FormItem>
        <BootstrapInput @bind-Value="@Context.Role_Name" IsTrim="true" ValidateRules="RolesDataRules" />
    </FormItem>
    <FormItem>
        <Select @bind-Value="@Context.Role_Status" />
    </FormItem>
    <FormItem>
            <AutoComplete Items="@cusids" ValueChanged="@CustsIdOnChanged" 
                          PlaceHolder="@(Context.Role_CustsName??"请输入所属客户")"
                          Debounce="1000" OnSelectedItemChanged="CustsIdOnValueChanged" DisplayText="所属客户" />
    </FormItem>
    <FormItem Cols="12">
        <Textarea @bind-Value="@Context.Role_Remark" rows="3" />
    </FormItem>
</Form>

@code {
    [Parameter]
    public RolesData Context { get; set; }

    private readonly List<string> _cusids = new();
    private IEnumerable<string> cusids => _cusids;
    private List<KeyValues> FilterDatas = new();
    private async Task CustsIdOnChanged(string val)
    {
        _cusids.Clear();
        FilterDatas = await UserService.GetCustsList(val);
        foreach (var item in FilterDatas)
        {
            if (!_cusids.Any(x => x == item.Key))
                _cusids.Add(item.Key!);
        }
    }

    private Task CustsIdOnValueChanged(string val)
    {
        Context.Role_Custs = Guid.Parse(FilterDatas.First(x => x.Key == val).Value!.ToString()!);
        return Task.CompletedTask;
    }

    private List<IValidator> RolesDataRules { get; } = new();
    /// <summary>
    /// OnInitialized
    /// </summary>
    protected override void OnInitialized()
    {
        base.OnInitialized();
        RolesDataRules.Add(new FormItemValidator(new FormVaildationAttribute((value, context) =>
        {
            switch (context.MemberName)
            {
                case "Role_Name":
                    var IsTobe = Task.Run(async () => await RoleService.CheckRoleNameRepeat((value as string)!)).GetAwaiter().GetResult();
                    return (!IsTobe, "角色名称已存在");
            }
            return FormVaildationResult.Success;
        })));
    }
}
